#import "BannerScrollView.h"
#import "clsFileFun.h"
#import "clsOtherFun.h"
#import "cImageView.h"



#define MARGIN 7.0
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define bgcolor [UIColor colorWithRed:115.0f/255.0f green:99.0f/255.0f blue:86.0f/255.0f alpha:1.0f]

@interface BannerScrollView () <UIScrollViewDelegate> {
    UIScrollView *_scrollView;
    
    NSLock *lock;
    NSInteger maxPreLoad;
    NSInteger maxCount;
    NSInteger currentPage;
    NSMutableDictionary *controlDic;
    NSTimer *time;
    UIPageControl *page;
    NSInteger _obannerSettingID;//纪录上次所点击的bannerId

}

@end


@implementation BannerScrollView

@synthesize list;
@synthesize parentVC;

- (void)dealloc {
    for (UIView *view in self.subviews) {
        if ([view isMemberOfClass:[cImageView class]]) {
            cImageView *imgView = (cImageView *)view;
            [imgView cancel];
        }
    }
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;

        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        [self addSubview:_scrollView];
    }
    return self;
}




- (void)loadData {
    self.backgroundColor = [UIColor whiteColor];
    _scrollView.backgroundColor = [UIColor whiteColor];
    
    CGFloat width = ScreenWidth;
    _scrollView.contentSize = CGSizeMake(width * [list count], 100);
    maxCount = [list count];
    _scrollView.scrollsToTop=NO;
    maxPreLoad = 5;
    currentPage = -1;
    [self prepareView:0];
    page = [[UIPageControl alloc]initWithFrame:CGRectMake(ScreenWidth/2-40, self.frame.size.height-30, 80, 30)];
    page.numberOfPages=list.count;
    page.pageIndicatorTintColor= [UIColor colorWithRed:246/255.0f green:89/255.0f blue:53/255.0f alpha:1];
    [page addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:page];
    time=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(AutoScroll) userInfo:nil repeats:YES];
}
-(void)nextAction:(id)sender
{
    [self prepareView:page.currentPage];
}
-(void)AutoScroll
{
    CGPoint currentPoint=_scrollView.contentOffset;
    if (currentPage==maxCount) {
        currentPage=1;
        currentPoint.x=(currentPage-1)*_scrollView.frame.size.width;
        [_scrollView scrollRectToVisible:CGRectMake(currentPoint.x, currentPoint.y, _scrollView.frame.size.width, _scrollView.frame.size.height) animated:NO];
    }else
    {
        currentPage+=1;
        currentPoint.x=(currentPage-1)*_scrollView.frame.size.width;
        [_scrollView scrollRectToVisible:CGRectMake(currentPoint.x, currentPoint.y, _scrollView.frame.size.width, _scrollView.frame.size.height) animated:YES];
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat pageWidth = _scrollView.frame.size.width;
    
    int pageindex = floor((_scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    [self prepareView:pageindex];
}

- (void)prepareView:(NSInteger)pageindex {
    [lock tryLock];
    
    if (currentPage == pageindex || pageindex < 0 || pageindex > [list count] - 1) {
        [lock unlock];
        return;
    }
    page.currentPage = pageindex;
    currentPage = pageindex;
    NSInteger startIndex = pageindex - maxPreLoad;
    NSInteger endIndex = pageindex + maxPreLoad;
    if (endIndex > maxCount - 1) {
        endIndex = maxCount - 1;
    }
    
    if (!controlDic) {controlDic = [NSMutableDictionary dictionary];}
    NSInteger count = [controlDic.allKeys count];
    for (NSInteger i = count - 1; i >= 0; i--) {
        NSNumber *number = [controlDic.allKeys objectAtIndex:i];
        if (number.integerValue < startIndex || number.integerValue > endIndex) {
            cImageView *view = [controlDic objectForKey:number];
            [view cancel];
            [view removeFromSuperview];
            [controlDic removeObjectForKey:number];
        }
    }
    
	CGRect rect = _scrollView.bounds;
	for (NSInteger i = startIndex; i <= endIndex; i++) {
        if (i < 0) {
            continue;
        }
        
        NSObject *obj = [controlDic objectForKey:[NSNumber numberWithInteger:i]];
        if (!obj) {
            rect.origin.x = rect.size.width * i;
            rect.origin.y = 0.0f;
            
            
            NSDictionary *dic = [list objectAtIndex:i];
            NSArray *array = [[dic objectForKey:@"url"] componentsSeparatedByString:@"/"];
            NSString *name = [array lastObject];
            NSString *url = [NSString stringWithFormat:@"%@",[array firstObject]];
            for (int i =1;i<array.count-1;i++) {
                url = [NSString stringWithFormat:@"%@/%@",url,array[i]];
            }
            cImageView *view = [[cImageView alloc] initWithFrame:rect];
            view.activityView.color = [UIColor blackColor];
            view.serverDirectory = url;
            view.localDirectory = [clsFileFun getBannerPhotoDir];
            view.saveName = name;
            view.noNetImage = [UIImage imageNamed:@""];
            view.errorImage = view.noNetImage;
            view.noImage = view.noNetImage;
            view.tag = [[dic objectForKey:@"SID"] integerValue];
            [view loadImage];
            [_scrollView addSubview:view];
            [controlDic setObject:view forKey:[NSNumber numberWithInteger:i]];
            
//            if (ocls.ActionType != 0) {
                view.userInteractionEnabled = YES;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBanner:)];
                [view addGestureRecognizer:tap];

//            }
        }
	}
    
    [lock unlock];
}

- (void)showBanner:(UITapGestureRecognizer *)tap {
    cImageView *view = (cImageView *)tap.view;
    _obannerSettingID = view.tag;
    
    [self getData];
}

-(void)getData{
    
    NSDictionary *clsBanner ;
    for (NSDictionary *ocls in list) {
        if (ocls) {
            NSInteger bannerSettingID = [[ocls objectForKey:@"SID"] integerValue];
            if (bannerSettingID == _obannerSettingID) {
                clsBanner = ocls;
                break;
            }
        }
    }
    if(![[clsBanner objectForKey:@""]isKindOfClass:[NSNull class]]){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[clsBanner objectForKey:@"WebUrl"]]];
    }
}


@end
